package com.buaa.multitythread;

import android.content.Entity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrator on 2016/4/20.
 */
public class ImageDownload {
    private String imageUrl;

    public ImageDownload(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public void loadImage(final ImageCallBack callBack){
        final Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                callBack.getDrawable((Drawable)msg.obj);
            }
        };
        //因为要在该类中开一个线程取网络图片，因此要使用接口回调方法
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                   /* HttpClient httpClient=new DefaultHttpClient();
                    HttpPost httpPost=new HttpPost(imageUrl);
                    HttpResponse httpResponse=httpClient.execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode()==200){
                        byte[] data= EntityUtils.toByteArray(httpResponse.getEntity());
                        Bitmap bitmap= BitmapFactory.decodeByteArray(data,0,data.length);*/
                        Drawable drawable=Drawable.createFromStream(new URL(imageUrl).openStream(),"");
                        Message message=Message.obtain();
                        message.obj=drawable;
                        handler.sendMessage(message);
                    } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    public interface ImageCallBack{
      public void getDrawable(Drawable drawable);
    }
}
